package zoran.wang.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import zoran.wang.entity.User;
import zoran.wang.utils.MD5Utils;

import javax.annotation.Resource;
import javax.annotation.Resources;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 用于SpringSecurity框架获取用户账密和角色
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    //模拟数据库中的用户数据
    static Map<String, User> map = new HashMap<String, User>();

    static {
        User user1 = new User();
        user1.setUsername("zhangsan");
        user1.setPassword("zhangsan");
        user1.setTelephone("123");

        User user2 = new User();
        user2.setUsername("lisi");
        user2.setPassword("lisi");
        user2.setTelephone("321");

        map.put(user1.getUsername(), user1);
        map.put(user2.getUsername(), user2);
    }

    /**
     * 根据用户名加载用户信息
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        System.out.println("username = " + username);

        //TODO：模拟根据输入进来的username查到数据库的数据
        User user = map.get(username);

        if (user == null) {
            System.out.println("用户名错误");
            return null;
        }

        //TODO：模拟查到数据库中的密码，加密，并进行拼接
        String rawPassword = user.getPassword();
        String md5password = MD5Utils.md5(rawPassword);
        String bcryPassword = new BCryptPasswordEncoder().encode(rawPassword);

        //TODO：模拟授权，需要改为查询数据库动态获得用户拥有的权限和角色
        List<GrantedAuthority> lists = new ArrayList<>();
        lists.add(new SimpleGrantedAuthority("add"));
        lists.add(new SimpleGrantedAuthority("delete"));
        lists.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

        return new org.springframework.security.core.userdetails.User(username, bcryPassword, lists);
    }
}
